
from django.http import JsonResponse
# Create your views here.
from . import models


def header_menu(request):

    menu_id = request.GET.get('menu_id', None)
    # 如果有 id 参数，
    if menu_id:
        try:
            menu = models.Menu.objects.get(id=menu_id)
            menu_data = {
                "name": menu.name,
                "path": menu.path,
                "icon": menu.icon,
                "order": menu.order
            }
            return JsonResponse(data={"data": menu_data, "msg": '获取菜单详情', "code": 200})
        except models.Menu.DoesNotExist:
            return JsonResponse(data={"code": 404, "msg": '菜单不存在', "data": None})
    # 否则，按列表处理
    menu_tag = request.GET.get('tag', '').strip()
    menus = models.Menu.objects.filter(
        tag=menu_tag, active=True).order_by('order')
    menu_list = []
    for menu in menus:
        menu_list.append({
            "name": menu.name,
            "path": menu.path,
            "icon": menu.icon,
            "order": menu.order
        })
    return JsonResponse(data={"data": menu_list, "msg": '获取标签对应的菜单路径', "code": 200})
